package com.wandousoushu.jiusen.ui.bookmail

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.adapter.BookMailAdapter
import com.wandousoushu.jiusen.bean.AdBean
import com.wandousoushu.jiusen.bean.BookMailBean
import com.wandousoushu.jiusen.ui.search.SearchActivity
import com.wandousoushu.jiusen.ui.widget.SearchView
import com.wandousoushu.jiusen.util.GsonUtils
import com.wandousoushu.jiusen.web.http.MainHttpUtils
import kotlinx.android.synthetic.main.layout_search_title_bar.*
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

class BookMailFragment : Fragment() {
    private var bookMailRecycerView: RecyclerView? = null
    private var refleshLinearout: LinearLayout? = null
    private var bookMainBeanList: List<BookMailBean>? = null
    private var adapter: BookMailAdapter? = null
    private var mAdBean: AdBean? = null
    private var adImageView: ImageView? = null
//    private var adTitleTextView: TextView? = null
//    private var adDownloadTextView: TextView? = null
    private var adUrl: String? = null
    private var searchView: SearchView? = null
    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_bookmail, container, false)
        bookMailRecycerView = root.findViewById<View>(R.id.bookmail_recycerview) as RecyclerView
        refleshLinearout = root.findViewById(R.id.bookmail_ll_reflesh)
        refleshLinearout!!.setOnClickListener(View.OnClickListener { HttpGetBoolMail() })
        //纵向线性布局
        val layoutManager = GridLayoutManager(requireContext(), 1)
        bookMailRecycerView!!.layoutManager = layoutManager
        adImageView = root.findViewById(R.id.bookmail_iv_ad)
        adImageView!!.setOnClickListener(View.OnClickListener { AdClick() })
//        adTitleTextView = root.findViewById(R.id.bookmail_ad_title)
//        adDownloadTextView = root.findViewById(R.id.bookmail_tv_download)
//        adDownloadTextView!!.setOnClickListener(View.OnClickListener { AdClick() })
        searchView = root.findViewById(R.id.bookmail_search_view)
        searchView!!.onActionViewExpanded()
        searchView!!.isSubmitButtonEnabled = true
        searchView!!.queryHint = getString(R.string.search_book_key)
        searchView!!.clearFocus()
        searchView!!.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                searchView!!.clearFocus()
                val intent = Intent(requireContext(), SearchActivity::class.java)
                intent.putExtra("key", query)
                startActivity(intent)
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                return false
            }
        })
        InitData()
        return root
    }

    private fun InitData() {
        HttpGetBoolMail()
        HttpGetBoolMailAd()
    }

    private fun AdClick() {
        if (adUrl != null) {
            val intent = Intent()
            intent.action = "android.intent.action.VIEW"
            val content_url = Uri.parse(adUrl) //此处填链接
            intent.data = content_url
            startActivity(intent)
        }
    }

    private fun HttpGetBoolMail() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBookMail() ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val bookList = GsonUtils.parseJArray(jsonObject.getString("data"), BookMailBean::class.java)
                    if (bookList == null || bookList!!.size == 0) return@Runnable
                    bookMainBeanList = bookList
                    mHandle.sendEmptyMessage(0)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetBoolMailAd() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBookMailAd() ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val adBean = GsonUtils.parseJObject(jsonObject.getString("data"), AdBean::class.java)
                            ?: return@Runnable
                    mAdBean = adBean
                    mHandle.sendEmptyMessage(3)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private val mHandle: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0 -> {
                    adapter = BookMailAdapter(requireContext(), bookMainBeanList)
                    adapter!!.setActionListener { bookBean ->
                        val intent = Intent(requireContext(), SearchActivity::class.java)
                        intent.putExtra("key", bookBean.name)
                        startActivity(intent)
                    }
                    bookMailRecycerView!!.adapter = adapter
                }
                1 -> Toast.makeText(requireContext(), resources.getString(R.string.bookmail_http_fail), Toast.LENGTH_SHORT).show()
                2 -> Toast.makeText(requireContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show()
                3 -> {
                    adUrl = mAdBean!!.url
                    //adDownloadTextView!!.text = mAdBean!!.title
                    setImageURL(mAdBean!!.pic)
                }
                4 -> adImageView!!.setImageBitmap(msg.obj as Bitmap)
                5 -> Toast.makeText(requireContext(), resources.getString(R.string.bookmail_http_ad_fail), Toast.LENGTH_SHORT).show()
            }
        }
    }

    //设置网络图片
    fun setImageURL(path: String?) {
        //开启一个线程用于联网
        object : Thread() {
            override fun run() {
                try {
                    //把传过来的路径转成URL
                    val url = URL(path)
                    //获取连接
                    val connection = url.openConnection() as HttpURLConnection
                    //使用GET方法访问网络
                    connection.requestMethod = "GET"
                    //超时时间为10秒
                    connection.connectTimeout = 10000
                    //获取返回码
                    val code = connection.responseCode
                    if (code == 200) {
                        val inputStream = connection.inputStream
                        //使用工厂把网络的输入流生产Bitmap
                        val bitmap = BitmapFactory.decodeStream(inputStream)
                        //利用Message把图片发给Handler
                        val msg = Message.obtain()
                        msg.obj = bitmap
                        msg.what = 4
                        mHandle.sendMessage(msg)
                        inputStream.close()
                    } else {
                        //服务启发生错误
                        mHandle.sendEmptyMessage(5)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                    //网络连接错误
                    mHandle.sendEmptyMessage(5)
                }
            }
        }.start()
    }
}